/**
 * Copyright (C) 2009 Marcel Urbanek
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.urbiworx.sugar;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

import javax.faces.component.UIOutput;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;


public class ClientStateOutput extends UIOutput {

	private SugarConfigurationEntry entry;
	
	public SugarConfigurationEntry getEntry() {
		return entry;
	}
	
	public ClientStateOutput()
	{
		;
	}
	public ClientStateOutput(SugarConfigurationEntry entry)
	{

		this.entry=entry;
	}
	@Override
	public void encodeEnd(FacesContext context) throws IOException {
		ResponseWriter writer=context.getResponseWriter();
		ByteArrayOutputStream baos=new ByteArrayOutputStream();		
		try {
			ObjectOutputStream oos=null;
			oos=new ObjectOutputStream(baos);
			oos.writeObject(SugarScopeHelper.getObjectForSugarEntry(entry));
			oos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		byte[] serobject=baos.toByteArray();	
		writer.startElement("input", this);
		writer.writeAttribute("type", "hidden", null);
		writer.writeAttribute("id", "client_"+entry.getName(), null);
		writer.writeAttribute("name", "client_"+entry.getName(), null);
		writer.writeAttribute("value", Base64.encodeBytes(serobject), null);
		writer.endElement("input");
	}
	@Override
	public void restoreState(FacesContext context, Object state) {	
		Object[] objectArray=(Object[])state;		
		super.restoreState(context, objectArray[0]);
		entry=(SugarConfigurationEntry)objectArray[1];		
	}
	@Override
	public Object saveState(FacesContext context) {
		Object[] objectArray=new Object[2];
		objectArray[0]=super.saveState(context);
		objectArray[1]=entry;
		return objectArray;
	}

}
